<template>
    <div class="login-container">
        <!-- 星空背景 -->
        <div class="starry-background">
            <div v-for="i in 100" :key="i" class="star" ></div>
        </div>

        <!-- 登录表单 -->
        <div class="login-form">
            <!-- Logo区域 -->
            <div class="logo-section">
                <div class="logo-icon">MES</div>
                <h1 class="logo-text">MES系统</h1>
                <!-- 添加欢迎标题 -->
                <h2 class="welcome-title">欢迎登录MES玩具小车制造系统</h2>
            </div>

            <!-- 表单区域 -->
            <form class="form" @submit.prevent="onSubmit">
                <!-- 用户名输入框 -->
                <div class="input-group captcha-group">
                    <div class="input-icon">
                        <svg viewBox="0 0 24 24" fill="currentColor">
                            <path
                                d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" />
                        </svg>
                    </div>
                    <input type="text" v-model="formData.username" placeholder="用户名" class="form-input" />
                </div>

                <!-- 密码输入框 -->
                <div class="input-group">
                    <div class="input-icon">
                        <svg viewBox="0 0 24 24" fill="currentColor">
                            <path
                                d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zM9 6c0-1.66 1.34-3 3-3s3 1.34 3 3v2H9V6zm9 14H6V10h12v10z" />
                        </svg>
                    </div>
                    <input type="password" v-model="formData.userPass" placeholder="密码" class="form-input"  show-password/>
                </div>

                <!-- 验证码输入框 -->
                <div class="input-group">
                    <div class="input-icon">
                        <svg viewBox="0 0 24 24" fill="currentColor">
                            <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z" /> 
                        </svg>
                    </div>
                    <input type="text" v-model="formData.setYzm" placeholder="请输入验证码结果" class="form-input" />
                    <div class="captcha-image">
                        <canvas ref="captchaCanvas" width="160" height="40" @click="generateCaptcha"></canvas>
                    </div>
                </div>
                <!-- 添加验证码提示信息 -->
                <div style="text-align: right; margin-top: -15px; margin-bottom: 15px; font-size: 12px; color: #999;">
                    验证码不区分大小写
                </div>

                <!-- 记住我选项 -->
                <div class="remember-me">
                    <label class="checkbox-container">
                        <input type="checkbox" v-model="formData.rememberMe" />
                        <span class="checkmark"></span>
                        <span class="checkbox-text">记住我</span>
                    </label>
                </div>

                <!-- 登录按钮 -->
                <button type="submit" class="login-btn" :disabled="isLoading">
                    <template v-if="isLoading">
                        <span class="loading-spinner" style="vertical-align: middle; margin-right: 8px;"></span>
                        <span>登录中...</span>
                    </template>
                    <template v-else>
                        <span>登录</span>
                    </template>
                </button>
                <div style="margin-top: 12px; text-align:center;">
                    <a href="javascript:void(0)" @click="goRegister" style="color:#1890ff;">还没有账号？去注册</a>
                </div>
            </form>
        </div>

        <!-- 底部版权信息 -->
        <div class="footer">
            <div class="copyright">
                Copyright © 2024 - 2025 皖ICP备2023011442号-1
            </div>
            <div class="police-info">
                <div class="police-icon">🚔</div>
                <span>苏公网安备32050602011976</span>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useCounterStore } from '../stores/counter'
const store = useCounterStore();
import { APIs, ShenchanInfoAPI } from '../Http/http'
const router = useRouter()
interface FormData {
    username: string
    userPass: string
    setYzm: string
    verificationCode: string
    rememberMe: boolean
}
//localhost
const formData = reactive<FormData>({
    username: 'admin',
    userPass: '123456',
    setYzm: "",
    verificationCode: '',
    rememberMe: false
})

const isLoading = ref(false)
const captchaCanvas = ref<HTMLCanvasElement>();

// 生成四位随机字母+数字组合验证码
const generateCaptcha = () => {
    if (!captchaCanvas.value) return

    const ctx = captchaCanvas.value.getContext('2d')
    if (!ctx) return

    const canvas = captchaCanvas.value
    const width = canvas.width
    const height = canvas.height

    // 清空画布
    ctx.clearRect(0, 0, width, height)

    // 设置背景
    ctx.fillStyle = '#f0f0f0'
    ctx.fillRect(0, 0, width, height)

    // 生成随机验证码（4位字母+数字组合）
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    let captchaText = ''
    for (let i = 0; i < 4; i++) {
        captchaText += chars.charAt(Math.floor(Math.random() * chars.length))
    }

    // 添加干扰线
    for (let i = 0; i < 3; i++) {
        ctx.strokeStyle = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`
        ctx.lineWidth = 1
        ctx.beginPath()
        ctx.moveTo(Math.random() * width, Math.random() * height)
        ctx.lineTo(Math.random() * width, Math.random() * height)
        ctx.stroke()
    }

    // 添加干扰点
    for (let i = 0; i < 30; i++) {
        ctx.fillStyle = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`
        ctx.beginPath()
        ctx.arc(Math.random() * width, Math.random() * height, 1, 0, 2 * Math.PI)
        ctx.fill()
    }

    // 添加验证码文字
    ctx.font = 'bold 24px Arial'
    ctx.fillStyle = '#333'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'

    for (let i = 0; i < captchaText.length; i++) {
        const x = (width / 5) * (i + 1)
        const y = height / 2 + (Math.random() - 0.5) * 15
        const rotation = (Math.random() - 0.5) * 0.3

        ctx.save()
        ctx.translate(x, y)
        ctx.rotate(rotation)
        ctx.fillText(captchaText.charAt(i), 0, 0)
        ctx.restore()
    }

    // 存储验证码用于验证
    formData.verificationCode = captchaText
}

const stat = ref({
    "loginId": 0,
    "logIp": "string",
    "addr": "string",
    "account": "string",
    "createTime": "2025-09-04T01:24:05.882Z"
})

// 提交表单
const onSubmit = async () => {
    if (isLoading.value) return
    if (!formData.username || !formData.userPass) {
        ElMessage.warning("请输入用户名和密码")
        return
    }
    if (!formData.setYzm) {
        ElMessage.warning("请输入验证码")
        return
    }
    // 验证字母数字组合验证码
    if (formData.setYzm.trim().toLowerCase() !== formData.verificationCode.trim().toLowerCase()) {
        ElMessage.error("验证码不正确")
        generateCaptcha()
        return
    }

    isLoading.value = true
    {
        const data = <any>stat.value;
        const res = await axios.post("http://101.37.80.143:8089/api/Write/Login", {
            userName: formData.username,
            userPass: formData.userPass,
            data: data
        })
        if (res.data.code == 100) {
            store.Users.userNickname = res.data.data.userNickname
            store.Users.rouleName = res.data.data.roleName
            store.Users.Token = res.data.token
            store.Users.rouleId = res.data.data.roleId
            store.Users.userId=res.data.data.userId
            ElMessage.success("登录成功")
            router.push({ path: "/DashboardView" })
        } else {
            ElMessage.error(res.data.msg)
            generateCaptcha()
        }
    }
}

const goRegister = () => {
    router.push('/register')
}

// 刷新验证码
const refreshCaptcha = () => {
    generateCaptcha()
}

onMounted(() => {
    nextTick(() => {
        generateCaptcha()
    })
})
</script>

<style scoped>
.login-container {
    width: 100%;
    height: 100vh;
    /* 移除原有的星空背景渐变，改为纯色背景 */
    background: #f0f2f5;
    position: relative;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-family: 'Arial', sans-serif;
    margin: 0;
    padding: 0;
}

/* 登录表单 */
.login-form {
    background: white;
    border-radius: 15px;
    padding: 40px;
    width: 100%;
    max-width: 400px;
    position: relative;
    z-index: 10;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

/* Logo区域 */
.logo-section {
    text-align: center;
    margin-bottom: 30px;
}

.logo-icon {
    width: 60px;
    height: 60px;
    background: linear-gradient(135deg, #1890ff, #40a9ff);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 15px;
    font-size: 24px;
    font-weight: bold;
    color: white;
    font-family: 'Courier New', monospace;
}

.logo-text {
    font-size: 2rem;
    font-weight: 700;
    color: #333;
    margin: 0 0 10px 0;
    letter-spacing: 2px;
}

/* 欢迎标题样式 */
.welcome-title {
    font-size: 1.1rem;
    font-weight: 500;
    color: #666;
    margin: 0;
}

/* 表单样式 */
.form {
    margin-bottom: 20px;
}

.input-group {
    position: relative;
    margin-bottom: 25px;
    display: flex;
    align-items: center;
}

.captcha-group {
    gap: 10px;
}

.input-icon {
    position: absolute;
    left: 15px;
    top: 50%;
    transform: translateY(-50%);
    color: #666;
    z-index: 2;
}

.input-icon svg {
    width: 20px;
    height: 20px;
}

.form-input {
    width: 100%;
    padding: 15px 15px 15px 50px;
    background: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 8px;
    color: #333;
    font-size: 16px;
    transition: all 0.3s ease;
    box-sizing: border-box;
}

.form-input::placeholder {
    color: #999;
}

.form-input:focus {
    outline: none;
    border-color: #1890ff;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 验证码图片 */
.captcha-image {
    width: 80px;
    height: 32px;
    border-radius: 4px;
    overflow: hidden;
    cursor: pointer;
    border: 1px solid #d9d9d9;
}

.captcha-image canvas {
    width: 100%;
    height: 100%;
}

/* 记住我选项 */
.remember-me {
    margin-bottom: 30px;
}

.checkbox-container {
    display: flex;
    align-items: center;
    cursor: pointer;
    color: #333;
}

.checkbox-container input[type="checkbox"] {
    display: none;
}

.checkmark {
    width: 18px;
    height: 18px;
    border: 2px solid #d9d9d9;
    border-radius: 3px;
    margin-right: 10px;
    position: relative;
    transition: all 0.3s ease;
    background: transparent;
}

.checkbox-container input[type="checkbox"]:checked+.checkmark {
    background: #1890ff;
    border-color: #1890ff;
}

.checkbox-container input[type="checkbox"]:checked+.checkmark::after {
    content: '✓';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: white;
    font-size: 12px;
    font-weight: bold;
}

.checkbox-text {
    font-size: 14px;
    color: #666;
}

/* 登录按钮 */
.login-btn {
    width: 100%;
    padding: 15px;
    background: linear-gradient(135deg, #1890ff, #40a9ff);
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.login-btn:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(24, 144, 255, 0.3);
}

.login-btn:active:not(:disabled) {
    transform: translateY(0);
}

.login-btn:disabled {
    opacity: 0.7;
    cursor: not-allowed;
}

/* 加载动画 */
.loading-spinner {
    display: inline-block;
    width: 20px;
    height: 20px;
    border: 2px solid rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    border-top-color: white;
    animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}

/* 底部版权信息 */
.footer {
    position: absolute;
    bottom: 20px;
    left: 0;
    right: 0;
    text-align: center;
    color: #666;
    font-size: 12px;
    z-index: 10;
}

.copyright {
    margin-bottom: 8px;
}

.police-info {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 5px;
}

.police-icon {
    font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 480px) {
    .login-form {
        margin: 20px;
        padding: 30px 25px;
    }

    .logo-text {
        font-size: 1.8rem;
    }

    .welcome-title {
        font-size: 1rem;
    }

    .form-input {
        font-size: 14px;
    }
}

/* 超小屏优化 */
@media (max-width: 360px) {
    .login-form {
        padding: 24px 18px;
    }

    .input-icon {
        left: 12px;
    }

    .form-input {
        padding: 14px 14px 14px 44px;
    }

    .captcha-image {
        width: 100px;
        height: 30px;
    }
}

/* 高清屏文本渲染微调 */
@media (min-resolution: 2dppx) {
    .login-form {
        box-shadow: 0 4px 25px rgba(0, 0, 0, 0.08);
    }
}
</style>